package com.llc.port.config;

import java.util.Iterator;
import java.util.Set;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.management.Query;

import org.springframework.context.annotation.Configuration;

/**
 * 	运行在tomcat等三方插件时，获取端口
 * @author linlvcao
 * @email 1013573731@qq.com
 * @time 2019年12月16日 下午4:40:18
 *
 */
@Configuration
public class GetPort {

    public int getPort() {
    	try {
            MBeanServer server;
            if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
                server = MBeanServerFactory.findMBeanServer(null).get(0);
            } else {
                return -1;
            }
     
            Set<ObjectName> names = server.queryNames(new ObjectName("Catalina:type=Connector,*"),
                    Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
     
            Iterator<ObjectName> iterator = names.iterator();
            if (iterator.hasNext()) {
                ObjectName name = iterator.next();
                return Integer.parseInt(server.getAttribute(name, "port").toString());
            }
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return -1;

    }

    
}
